#include <stdio.h>
#include <stdlib.h>
//#include <sndfile.h>
#include "g711.h"
#include "portaudio.h"

#define SAMPLE_RATE 8000
#define NUM_CHANNELS 1
#define SAMPLE_FORMAT paInt16
#define FRAMES_PER_BUFFER 1024

//#define FILENAME "/Users/lingyu/Downloads/output.pcm"
#define FILENAME "/home/liws/Downloads/output.pcm"

//SNDFILE *file;
FILE *alawFile;
//SF_INFO sfinfo;

static int paCallback(const void *inputBuffer, void *outputBuffer,
                      unsigned long framesPerBuffer,
                      const PaStreamCallbackTimeInfo *timeInfo,
                      PaStreamCallbackFlags statusFlags,
                      void *userData) {
    short *samples = (short *)inputBuffer;
    int size = framesPerBuffer * NUM_CHANNELS; //* sizeof(short);
    unsigned char* g711aData = malloc(size);
//
    encodeG711a(g711aData, samples, size);


    fwrite(g711aData, sizeof(int16_t), size, alawFile);


    // 写入音频数据到文件
//    short *in = (short*)inputBuffer;
////    sf_writef_float(file, in, framesPerBuffer);
//    sf_writef_short(file, in, framesPerBuffer);

    return paContinue;
}

int main(void) {
    PaStream *stream;
    PaError err;

    // 打开文件以保存音频数据
//    sfinfo.channels = NUM_CHANNELS;
//    sfinfo.samplerate = SAMPLE_RATE;
//    sfinfo.format = SF_FORMAT_WAV |SF_FORMAT_PCM_16;
//    file = sf_open(FILENAME, SFM_WRITE, &sfinfo);
//    if (!file) {
//        fprintf(stderr, "Error opening file %s for writing.\n", FILENAME);
//        return -1;
//    }

    alawFile = fopen(FILENAME, "wb");

    // 初始化 PortAudio
    err = Pa_Initialize();
    if (err != paNoError) {
        fprintf(stderr, "PortAudio initialization failed: %s\n", Pa_GetErrorText(err));
        return -1;
    }

    // 打开默认输入设备
    PaStreamParameters inputParameters;
    inputParameters.device = Pa_GetDefaultInputDevice();
    if (inputParameters.device == paNoDevice) {
        fprintf(stderr, "Error: No default input device.\n");
        Pa_Terminate();
        return -1;
    }
    inputParameters.channelCount = NUM_CHANNELS;
    inputParameters.sampleFormat = SAMPLE_FORMAT;
    inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    // 打开音频流
    err = Pa_OpenStream(&stream,
                        &inputParameters,
                        NULL, // no output
                        SAMPLE_RATE,
                        FRAMES_PER_BUFFER,
                        paClipOff,
                        paCallback,
                        NULL); // no user data
    if (err != paNoError) {
        fprintf(stderr, "Error opening audio stream: %s\n", Pa_GetErrorText(err));
        Pa_Terminate();
        fclose(alawFile);
//        sf_close(file);
        return -1;
    }

    // 启动音频流
    err = Pa_StartStream(stream);
    if (err != paNoError) {
        fprintf(stderr, "Error starting audio stream: %s\n", Pa_GetErrorText(err));
        Pa_CloseStream(stream);
        Pa_Terminate();
        fclose(alawFile);
//        sf_close(file);
        return -1;
    }

    printf("Press Enter to stop the audio stream...\n");
    getchar(); // 等待用户按下 Enter 键

    // 停止和关闭音频流
    err = Pa_StopStream(stream);
    if (err != paNoError) {
        fprintf(stderr, "Error stopping audio stream: %s\n", Pa_GetErrorText(err));
    }

    err = Pa_CloseStream(stream);
    if (err != paNoError) {
        fprintf(stderr, "Error closing audio stream: %s\n", Pa_GetErrorText(err));
    }

    // 终止 PortAudio
    Pa_Terminate();

    // 关闭文件
//    sf_close(file);
    fclose(alawFile);

    printf("Audio stream stopped. Audio data saved to %s\n", FILENAME);
}
